package com.seqb.system.filter;

import com.seqb.utils.JsoupUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * <code>{@link XssWrapper}</code>
 *
 * @author win7
 */
public class XssWrapper extends HttpServletRequestWrapper {
    HttpServletRequest orgRequest = null;
    private boolean isIncludeRichText = false;
    private String currentUrl;
    private static Logger logger = LoggerFactory.getLogger(JsoupUtils.class);
    private static String key = "and|exec|insert|select|delete|update|count|truncate|declare";
    private static Set<String> notAllowedKeyWords = new HashSet<String>(0);
    private static String replacedString = "INVALID";

    static {
        String[] keyStr = key.split("\\|");
        for (String str : keyStr) {
            notAllowedKeyWords.add(str);
        }
    }

    public XssWrapper(HttpServletRequest request, boolean isIncludeRichText) {
        super(request);
        orgRequest = request;
        this.isIncludeRichText = isIncludeRichText;
        currentUrl = request.getRequestURI();
    }

    /**
     * 覆盖getParameter方法，将参数名和参数值都做xss过滤。<br/>
     * 如果需要获得原始的值，则通过super.getParameterValues(name)来获取<br/>
     * getParameterNames,getParameterValues和getParameterMap也可能需要覆盖
     */
    @Override
    public String getParameter(String name) {
        Boolean flag = ("content".equals(name) || name.endsWith("WithHtml"));
        if (flag && !isIncludeRichText) {
            return super.getParameter(name);
        }
        name = cleanXss(name);
        String value = super.getParameter(name);
        if (StringUtils.isNotBlank(value)) {
            value = cleanXss(value);
        }
        return value;
    }

    @Override
    public String[] getParameterValues(String name) {
        Boolean flag = ("content".equals(name) || name.endsWith("WithHtml"));
        if (flag && !isIncludeRichText) {
            return super.getParameterValues(name);
        }
        String[] arr = super.getParameterValues(name);
        if (arr != null) {
            for (int i = 0; i < arr.length; i++) {
                arr[i] = cleanXss(arr[i]);
            }
        }
        return arr;
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        Map<String, String[]> values = super.getParameterMap();
        if (values == null) {
            return null;
        }
        Map<String, String[]> result = new HashMap<>(16);
        for (String key : values.keySet()) {
            String encodedKey = "";
            Boolean flag = ("content".equals(key) || key.endsWith("WithHtml"));
            if (flag && !isIncludeRichText) {
                encodedKey = key;
            } else {
                encodedKey = cleanXss(key);
            }
            int count = values.get(key).length;
            String[] encodedValues = new String[count];
            for (int i = 0; i < count; i++) {
                if (flag && !isIncludeRichText) {
                    encodedValues[i] = values.get(key)[i];
                } else {
                    encodedValues[i] = cleanXss(values.get(key)[i]);
                }
            }
            result.put(encodedKey, encodedValues);
        }
        return result;
    }

    /**
     * 覆盖getHeader方法，将参数名和参数值都做xss过滤。<br/>
     * 如果需要获得原始的值，则通过super.getHeaders(name)来获取<br/>
     * getHeaderNames 也可能需要覆盖
     */
    @Override
    public String getHeader(String name) {
        name = cleanXss(name);
        String value = super.getHeader(name);
        if (StringUtils.isNotBlank(value)) {
            value = cleanXss(value);
        }
        return value;
    }

    /**
     * 获取最原始的request
     *
     * @return
     */
    public HttpServletRequest getOrgRequest() {
        return orgRequest;
    }

    /**
     * 获取最原始的request的静态方法
     *
     * @return
     */
    public static HttpServletRequest getOrgRequest(HttpServletRequest req) {
        if (req instanceof XssWrapper) {
            return ((XssWrapper) req).getOrgRequest();
        }
        return req;
    }

    private String cleanXss(String value) {
        value = JsoupUtils.clean(value);
        value = cleanSqlKeyWords(value);
        return value;
    }

    private String cleanSqlKeyWords(String value) {
        String paramValue = value;
        for (String keyword : notAllowedKeyWords) {
            boolean flag = paramValue.length() > keyword.length() + 4 && (paramValue.contains(" " + keyword)
                    || paramValue.contains(keyword + " ") || paramValue.contains(" " + keyword + " "));
            if (flag) {
                paramValue = StringUtils.replace(paramValue, keyword, replacedString);
                logger.error(this.currentUrl + "已被过滤，因为参数中包含不允许sql的关键词(" + keyword + ")" + ";参数：" + value + ";过滤后的参数：" + paramValue);
            }
        }
        return paramValue;
    }
}
